import 'package:dio/dio.dart';
import 'package:gold/app/user_provider.dart';
import 'package:gold/generated/json/base/json_convert_content.dart';
import 'package:gold/route/xfg_nav.dart';
import 'package:gold/utils/cache_data.dart';
import 'package:gold/utils/xfg_utils.dart';

import 'http.dart';

/// @description:
/// @author tangzhentao
/// @created at 20:22 2023/6/5

/// 网络请求拦截器
class ApiInterceptor extends InterceptorsWrapper {
  @override
  void onRequest(RequestOptions options, RequestInterceptorHandler handler) {
    /// token验证
    options.headers['Authorization'] =  'Bearer ${CacheData().authorization}';
    handler.next(options);
  }

  @override
  void onResponse(Response response, ResponseInterceptorHandler handler) async {
    /// token无效需要重新登录
    if (response.statusCode == 401) {
      await XfgNav.read<UserProvider>().signOut();
    } else {
      final data = response.data;
      if (data is Map) {
        final code = jsonConvert.convert<int>(data['code']);
        if (code == HttpErrorType.invalidToken) await XfgNav.read<UserProvider>().signOut();
      }
    }
    handler.next(response);
  }

  @override
  void onError(DioException err, ErrorInterceptorHandler handler) {
    xfgPrint.call('错误数据(${err.message}):${err.response?.statusCode}');
    // if (err.response?.statusCode == 401) Provider.of<UserProvider>(WsNav.currentContext, listen: false).signOut(sync: false);
    handler.next(err);
  }
}